package com.simplegovern.authority.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.simpleframe.persistence.hibernate.Page;
import com.simpleframe.persistence.hibernate.Searcher;
import com.simpleframe.security.AuthorityContext;
import com.simpleframe.security.Role;
import com.simplegovern.authority.SysRole;
import com.simplegovern.authority.SysRoleAction;
import com.simplegovern.authority.dao.ActiontypeDAO;
import com.simplegovern.authority.dao.RoleDAO;

public class RoleService {

	@Autowired
	private RoleDAO roleDAO;
	@Autowired
	private RoleActionService roleActionService;
	
	public SysRole getById(long id){
		return roleDAO.findById(id);
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void deletes(Long[] ids){
		for (Long id : ids) {
			roleDAO.delete(id);
			roleActionService.remove(id);
			//删除内存数据
			AuthorityContext.deleteRole(id);
		}
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void create(SysRole role, Long[] actionIds){
		roleDAO.save(role);
		roleActionService.add(actionIds, role.getId());
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void update(SysRole role, Long[] actionIds){
		roleDAO.update(role);
		roleActionService.remove(role.getId());
		roleActionService.add(actionIds, role.getId());
	}
	
	public void addRoleCache(SysRole sr){
		System.out.println("添加到内存role:"+sr.getName());
		Role role = new Role();
		role.setId(sr.getId());
		role.setName(sr.getName());
		//为角色添加权限
		List<SysRoleAction> sras = roleActionService.getRoleActionList(sr.getId());
		for (SysRoleAction sra : sras) {
			role.addAction(AuthorityContext.getAction(String.valueOf(sra.getActionId())));
		}
		AuthorityContext.addRole(role);
	}
	
	public List<SysRole> getRoles(){
		return roleDAO.loadAll();
	}
	
	//以上自动生成
	
	public Page getPage(Searcher searcher){
		return roleDAO.getPage(searcher);
	}

}
